package org.ifilm.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.ifilm.model.User;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public User createUser(User user) {
		return entityManager.merge(user);
	}

	@Override
	public User getUser(String email, String password) {
		try {
			Query query = entityManager.createQuery(getUserQuery());
			query.setParameter("email", email);
			query.setParameter("password", password);
			
			return (User)query.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String getUserQuery() {
		StringBuilder strBuild = new StringBuilder();
		//TODO returning only u.id might be enough
		strBuild.append("select u from user u where (u.email=:email) and (u.password=:password)");
		return strBuild.toString();
	}
}